﻿using System;
using JsonConverter.Converter;

namespace JsonConverter.Writer
{
    public abstract class JsonWriter: IDisposable
    {
        protected ConverterProvider ConverterProvider { get; private set; }

        protected JsonWriter() : this(null) { }

        protected JsonWriter(ConverterProvider converterProvider)
        {
            ConverterProvider = converterProvider ?? ConverterProvider.Default;
        }

        public virtual void WriteLiteral(string s)
        {
            OnWriteLiteral(s);
        }

        protected abstract void OnWriteLiteral(string jsonString);

        public virtual void Write(object value)
        {
            IConverter converter;
            if (value == null)
            {
                converter = ConverterProvider.NullConverter;
            }
            else
            {
                converter = ConverterProvider[value.GetType()];
            }

            if (converter is PrimitiveConverter)
            {
                OnWriteLiteral(((IPrimitiveConverter) converter).Convert(value));
            }
            else
            {
                ((IObjectConverter) converter).Convert(this, value);
            }
        }

        public virtual void Dispose() { }
    }
}
